<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Agent;
use App\Models\Registry;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Vinlon\Laravel\LayAdmin\PaginateResponse;

class RegistryController extends Controller
{
    /** 列表查询 */
    public function index()
    {
        $query = Registry::query()
            ->with(['agent', 'user.auth'])
            ->when(request()->agent_id, function ($q) {
                return $q->where('agent_id', request()->agent_id);
            })
            ->when(request()->keyword, function ($q) {
                $likeVal = '%' . request()->keyword . '%';

                return $q->where('product_name', 'like', $likeVal)->orWhere('register_id', 'like', $likeVal);
            })
            ->when(request()->mobile, function ($q) {
                return $q->whereHas('user', function ($q2) {
                    $likeVal = '%' . request()->mobile . '%';

                    return $q2->where('mobile', 'like', $likeVal);
                });
            })
            ->when(request()->start_date, function ($q) {
                return $q->whereDate('created_at', '>=', request()->start_date);
            })
            ->when(request()->end_date, function ($q) {
                return $q->whereDate('created_at', '>=', request()->end_date);
            })
            ->when(request()->status, function ($q) {
                return $q->where('status', request()->status);
            })
            ->when(request()->year, function ($q) {
                return $q->whereYear('created_at', request()->year);
            })
            ->when(request()->month, function ($q) {
                return $q->whereMonth('created_at', request()->month);
            })
            ->orderByDesc('id');

        return paginate_result($query);
    }

    /** 查看登记详情 */
    public function show($id)
    {
        $registry = Registry::query()->find($id);
        $registry->load([
            'agent', 'user', 'order', 'productFiles', 'productImages',
            'authors', 'owners', 'attachFiles', 'auditHistories',
        ]);

        return $registry->toArray();
    }

    public function getSettleMonths()
    {
        return Registry::query()
            ->select([
                DB::raw('year(created_at) as year'),
                DB::raw('month(created_at) as month'),
            ])
            ->orderByDesc('year')->orderByDesc('month')
            ->get()
            ->mapWithKeys(function (Registry $registry) {
                return [
                    $registry->year . '-' . Str::padRight('0', 2, $registry->month) => $registry->year . '年' . $registry->month . '月',
                ];
            })->toArray();
    }

    /** 查看月结汇总 */
    public function getSettleSummary()
    {
        $page = request()->get('page', 1);
        $limit = request()->get('limit', 10);

        $query = Registry::query()
            ->when(request()->agent_id, function ($q) {
                return $q->where('agent_id', request()->agent_id);
            })
            ->when(request()->month, function ($q) {
                return $q->where('created_at', 'like', request()->month . '%');
            });

        $count = $query->count(DB::raw('distinct agent_id, year(created_at), month(created_at)'));

        $summaries = $query->with(['agent'])
            ->select([
                'agent_id',
                DB::raw('year(created_at) as year'),
                DB::raw('month(created_at) as month'),
                DB::raw('count(*) as count'),
            ])
            ->groupBy([
                'agent_id', 'year', 'month',
            ])
            ->orderByDesc('year')->orderByDesc('month')
            ->offset(($page - 1) * $limit)->limit($limit)
            ->get();

        return new PaginateResponse($count, $summaries);
    }

    /** 下载月结明细 */
    public function exportMonthSettleDetail()
    {
        request()->validate([
            'agent_id' => 'required',
            'year' => 'required',
            'month' => 'required',
        ]);

        $agentId = request()->agent_id;
        $year = request()->year;
        $month = request()->month;
        $agent = Agent::query()->find($agentId);

        $registries = Registry::query()
            ->with(['user'])
            ->where('agent_id', $agentId)
            ->whereYear('created_at', $year)
            ->whereMonth('created_at', $month)
            ->get();

        $fileName = sprintf(
            '登记列表-%s-%s年%s月_%s.csv',
            $agent->name,
            $year,
            $month,
            now()->format('YmdHis')
        );
        $dir = storage_path('app/export/' . today()->format('Ymd'));
        if (!is_dir($dir)) {
            mkdir($dir, 0755, true);
        }
        $path = $dir . '/' . $fileName;
        $file = fopen($path, 'w');
        fwrite($file, chr(0xEF) . chr(0xBB) . chr(0xBF));
        $header = ['登记用户', '作品名称', '作品分类', '费用', '提交时间', '状态'];
        fputcsv($file, $header);
        foreach ($registries as $registry) {
            $row = [
                $registry->user->mobile,
                $registry->product_name,
                $registry->product_cat,
                $registry->display_pay_amount,
                $registry->created_at->toDateTimeString(),
                $registry->status->description,
            ];
            fputcsv($file, $row);
        }
        fclose($file);

        return response()->download($path, $fileName, [
            'Content-Type' => 'text/csv',
        ]);
    }
}
